package com.moco.launcher.activity;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;

import com.moco.launcher.R;
import com.moco.launcher.alarm.Alarm;
import com.moco.launcher.alarm.StaticWakeLock;
import com.oazon.common.Logger;

public class AlarmAlertActivity extends BaseActivity implements OnClickListener {
	private final static String TAG = "AlarmAlertActivity";
	
	private Alarm mAlarm;
	private MediaPlayer mPlayer;
	private ImageButton mBtnCancel;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.alarm_activity_alert);
		
		mBtnCancel = (ImageButton) findViewById(R.id.alarm_alert_cancel);
		mBtnCancel.setOnClickListener(this);

		Bundle bundle = this.getIntent().getExtras();
		if (bundle != null)
			mAlarm = (Alarm) bundle.getSerializable("alarm");
		
		TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		PhoneStateListener phoneStateListener = new PhoneStateListener() {
			@Override
			public void onCallStateChanged(int state, String incomingNumber) {
				switch (state) {
				case TelephonyManager.CALL_STATE_RINGING:
					Logger.d(getClass().getSimpleName(), "Incoming call: " + incomingNumber);
					try {
						mPlayer.pause();
					} catch (IllegalStateException e) {
					}
					break;
				case TelephonyManager.CALL_STATE_IDLE:
					Logger.d(getClass().getSimpleName(), "Call State Idle");
					try {
						mPlayer.start();
					} catch (IllegalStateException e) {
					}
					break;
				}
				
				super.onCallStateChanged(state, incomingNumber);
			}
		};

		telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
		startAlarm();
	}

	private void startAlarm() {
		if (mAlarm.getAlarmTonePath() != "") {
			mPlayer = new MediaPlayer();
			try {
				mPlayer.setVolume(1.0f, 1.0f);
				mPlayer.setDataSource(this, Uri.parse(mAlarm.getAlarmTonePath()));
				mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
				mPlayer.setLooping(true);
				mPlayer.prepare();
				mPlayer.start();
			} catch (Exception e) {
				mPlayer.release();
			}
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.alarm_alert_cancel:
			try {
				mPlayer.stop();
			} catch (IllegalStateException ise) {
			}
			
			try {
				mPlayer.release();
			} catch (Exception e) {
			}
			
			this.finish();
			break;
		}

	}

	@Override
	protected void onPause() {
		super.onPause();
		
		StaticWakeLock.lockOff(this);
	}

	@Override
	protected void onDestroy() {
		try {
			mPlayer.stop();
		} catch (Exception e) {
		}
		
		try {
			mPlayer.release();
		} catch (Exception e) {
		}
		
		super.onDestroy();
	}
}
